﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Specialized;


namespace Gollie
{
	public class ConfigAppSettings
	{
		private static ConfigAppSettings appSettings = null;
		private Dictionary<string, string> keys = new Dictionary<string,string>(32);
		private static string buildNumber = null;

		private ConfigAppSettings()
		{
			SetAppSettings();
		}

		private void SetAppSettings()
		{
			Regex regex = new Regex(@"\$\{(.+?)?}", RegexOptions.Compiled);
			foreach (string key in System.Configuration.ConfigurationManager.AppSettings)
			{
				string val = System.Configuration.ConfigurationManager.AppSettings[key];

				foreach (Match match in regex.Matches(val))
				{
					string variable = match.Groups[1].Value;

					string replaceBy = System.Configuration.ConfigurationManager.AppSettings[variable];

					val = val.Replace(match.Value, replaceBy);
				}

				keys[key] = val;
			}
			
			//On purpose: throw exception if not found. Buildnumber needs to be present in web.config.
			buildNumber = keys["buildnumber"];
		}

		public IEnumerable<KeyValuePair<string, string>> GetAutoCSSIncludes()
		{
			return Instance.keys.Where<KeyValuePair<string, string>>(k => k.Key.StartsWith("css-auto-include"));
		}

		public IEnumerable<KeyValuePair<string, string>> GetAutoJSIncludes()
		{
			return Instance.keys.Where<KeyValuePair<string, string>>(k => k.Key.StartsWith("js-auto-include"));
		}

		public static ConfigAppSettings Instance
		{
			get
			{
				if (appSettings == null)
					appSettings = new ConfigAppSettings();

				return appSettings;
			}
		}

		public static string GetValue(string key)
		{
			string retVal = null;

			Instance.keys.TryGetValue(key, out retVal);

			return retVal;
		}

		public static string BuildNumber
		{
			get { return buildNumber != null ? buildNumber : GetValue("buildnumber"); }
		}
	}
}